#include "characterclassform.h"
#include "ui_characterclassform.h"
#include "dtwentymodel.h"
#include "characterclassmodel.h"


CharacterClassForm::CharacterClassForm(QWidget *parent) :
    AbstractEditor(parent),
    ui(new Ui::CharacterClassForm)
{
    ui->setupUi(this);

    ui->treeView->setModel(new CharacterClassModel(this));
}

CharacterClassForm::~CharacterClassForm()
{
    delete ui;
}

void CharacterClassForm::setEditorData(QAbstractItemModel *model, const QModelIndex &index)
{
    CharacterClassModel* proxy = qobject_cast<CharacterClassModel*>(ui->treeView->model());

    proxy->setSourceModel(model);
    QModelIndex proxyIndex = proxy->mapFromSource(index);

    if (!model || !proxyIndex.isValid())
    {
        /// \todo: Error handling
        /// \author: jussi
        /// \date: 2013-0705

        return;
    }

    ui->treeView->setRootIndex(proxyIndex);

    /// \todo:  Magic number for name column needs to be defined appropriately.
    /// \author: jussi
    /// \date:  2013-07-05
    QModelIndex nameIndex = proxyIndex.sibling(proxyIndex.row(), 0);
    ui->lineEdit->setText(nameIndex.data().toString());

    QModelIndex childProxy = proxyIndex.child(0,0);
    while (childProxy.isValid())
    {
        ui->treeView->expand(childProxy);
        childProxy = childProxy.sibling(childProxy.row()+1, childProxy.column());
    }

    ui->treeView->hideColumn(1);

}

void CharacterClassForm::on_lineEdit_editingFinished()
{
    QModelIndex nameIndex = ui->treeView->rootIndex();

    /// \todo:  Magic number for name column needs to be defined appropriately.
    /// \author: jussi
    /// \date:  2013-07-05
    nameIndex = nameIndex.sibling(nameIndex.row(), 0);

    ui->treeView->model()->setData(nameIndex, ui->lineEdit->text());
}
